package com.wenzhoujie;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.wenzhoujie.library.title.SDTitleSimple.SDTitleSimpleListener;
import com.wenzhoujie.library.utils.SDHandlerUtil;
import com.wenzhoujie.library.utils.SDToast;
import com.wenzhoujie.library.utils.SDViewBinder;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lingou.www.R;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.bean.SocializeEntity;
import com.umeng.socialize.controller.listener.SocializeListeners.SnsPostListener;
import com.umeng.socialize.media.UMImage;
import com.wenzhoujie.app.App;
import com.wenzhoujie.app.AppHelper;
import com.wenzhoujie.common.ImageLoaderManager;
import com.wenzhoujie.constant.ApkConstant;
import com.wenzhoujie.constant.Constant.TitleType;
import com.wenzhoujie.http.InterfaceServer;
import com.wenzhoujie.model.LocalUserModel;
import com.wenzhoujie.model.RequestModel;
import com.wenzhoujie.model.act.BaseActModel;
import com.wenzhoujie.umeng.UmengSocialManager;
import com.wenzhoujie.utils.IocUtil;
import com.wenzhoujie.utils.JsonUtil;
import com.wenzhoujie.utils.SDFileUtil;
import com.wenzhoujie.utils.SDImageUtil;
import com.wenzhoujie.utils.SDIntentUtil;
import com.wenzhoujie.utils.SDInterfaceUtil;
import com.wenzhoujie.utils.SDTypeParseUtil;
import com.wenzhoujie.utils.ViewInject;

public class TakephotosActivity extends BaseActivity implements OnClickListener
{
	private static final String IMAGE_NAME_TEMP = "share_temp.jpg";
	private static final String IMAGE_NAME_UPLOAD = "share_upload.jpg";

	private static final int MAX_INPUT_NUMBER = 140;

	public static final int REQUEST_CODE_TAKE_PHOTO = 10;
	public static final int REQUEST_CODE_SELECT_PHOTO = 11;

	private static final int MAX_UPLOAD_IMAGE_SIZE = 1024 * 1024;

	@ViewInject(id = R.id.act_takephotos_et_content)
	private EditText mEtContent = null;

	@ViewInject(id = R.id.act_takephotos_ll_take_photo)
	private LinearLayout mLlTakePhoto = null;

	@ViewInject(id = R.id.act_takephotos_ll_share)
	private LinearLayout mLlShare = null;

	@ViewInject(id = R.id.act_takephotos_ll_jing)
	private LinearLayout mLlJing = null;

	@ViewInject(id = R.id.act_takephotos_ll_at)
	private LinearLayout mLlAt = null;

	@ViewInject(id = R.id.act_takephotos_ll_text_number)
	private LinearLayout mLlTextNumber = null;

	@ViewInject(id = R.id.act_takephotos_tv_text_number)
	private TextView mTvTextNumber = null;

	@ViewInject(id = R.id.act_takephotos_rl_take_photo)
	private RelativeLayout mRlTakePhoto = null;

	@ViewInject(id = R.id.act_takephotos_ib_take_photo)
	private ImageButton mIbTakePhoto = null;

	@ViewInject(id = R.id.act_takephotos_ib_album)
	private ImageButton mIbAlbum = null;

	@ViewInject(id = R.id.act_takephotos_rl_take_result)
	private RelativeLayout mRlTakeResult = null;

	@ViewInject(id = R.id.act_takephotos_iv_result_image)
	private ImageView mIvResultImage = null;

	@ViewInject(id = R.id.act_takephotos_ib_result_image_close)
	private ImageButton mIbResultImageClose = null;

	private List<View> mListContent = new ArrayList<View>();

	private String is_syn_sina = "0";
	private String is_syn_tencent = "0";
	private String mStrContent = null;

	private File mFileImage = null;
	private File mFileImageCompress = null;

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setmTitleType(TitleType.TITLE_SIMPLE);
		setContentView(R.layout.act_takephotos);
		IocUtil.initInjectedView(this);
		init();
	}

	private void init()
	{
		addFrameLayouts();
		initTitle();
		registeClick();
		addEdittextListener();
	}

	/**
	 * 输入框监听
	 */
	private void addEdittextListener()
	{
		mEtContent.setFilters(new InputFilter[] { new InputFilter.LengthFilter(MAX_INPUT_NUMBER) });
		mEtContent.addTextChangedListener(new TextWatcher()
		{
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count)
			{

			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after)
			{

			}

			@Override
			public void afterTextChanged(Editable s)
			{
				int inputLength = s.toString().length();
				mTvTextNumber.setText(String.valueOf(MAX_INPUT_NUMBER - inputLength));
			}
		});
	}

	private void addFrameLayouts()
	{
		mListContent.add(mRlTakePhoto);
		mListContent.add(mRlTakeResult);
	}

	private void initTitle()
	{
		mTitleSimple.setmListener(new SDTitleSimpleListener()
		{

			@Override
			public void onRightButtonCLick_SDTitleSimple(View v)
			{
				clickPublish();
			}

			@Override
			public void onLeftButtonCLick_SDTitleSimple(View v)
			{
				finish();
			}
		});
		mTitleSimple.setTitleTop("我要分享");
		mTitleSimple.setRightText("发表");
	}

	/**
	 * 发表按钮被点击
	 */
	protected void clickPublish()
	{
		if (validateParams())
		{
			LocalUserModel user = App.getApplication().getmLocalUser();
			if (user != null)
			{
				RequestModel model = new RequestModel();
				model.put("act", "addshare");
				model.put("pwd", user.getUser_pwd());
				model.put("content", mStrContent);
				model.put("email", user.getUser_name());
				model.put("source", "来自Android客户端");
				model.put("type", "android");
				model.put("is_syn_sina", is_syn_sina);
				model.put("is_syn_tencent", is_syn_tencent);
				if (mFileImageCompress != null)
				{
					model.putFile("image_1", mFileImageCompress);
				}
				RequestCallBack<String> handler = new RequestCallBack<String>()
				{

					@Override
					public void onStart()
					{
						AppHelper.showLoadingDialog("请稍候...");
					}

					@Override
					public void onSuccess(ResponseInfo<String> responseInfo)
					{
						BaseActModel actModel = JsonUtil.json2Object(responseInfo.result, BaseActModel.class);
						if (!SDInterfaceUtil.isActModelNull(actModel))
						{
							if (actModel.getResponse_code() == 1)
							{
								if (SDTypeParseUtil.getIntFromString(actModel.getStatus(), 0) == 1)
								{
									Intent intent = new Intent(TakephotosActivity.this, MyPublishActivity.class);
									startActivity(intent);
									finish();
								}
							}
						}
					}

					@Override
					public void onFailure(HttpException error, String msg)
					{

					}

					@Override
					public void onFinish()
					{
						AppHelper.hideLoadingDialog();
					}
				};
				InterfaceServer.getInstance().requestInterface(model, handler);
			} else
			{
				SDToast.showToast("亲，您还未登录");
				startActivity(new Intent(getApplicationContext(), LoginNewActivity.class));
			}
		}
	}

	/**
	 * 验证发表参数是否合法
	 * 
	 * @return
	 */
	private boolean validateParams()
	{
		mStrContent = mEtContent.getText().toString();
		if (TextUtils.isEmpty(mStrContent))
		{
			SDToast.showToast("请输入内容后再提交");
			mEtContent.requestFocus();
			return false;
		}
		return true;
	}

	private void registeClick()
	{
		mLlTakePhoto.setOnClickListener(this);
		mLlShare.setOnClickListener(this);
		mLlJing.setOnClickListener(this);
		mLlAt.setOnClickListener(this);
		mLlTextNumber.setOnClickListener(this);
		mIbTakePhoto.setOnClickListener(this);
		mIbResultImageClose.setOnClickListener(this);
		mIbAlbum.setOnClickListener(this);
	}

	@Override
	public void onClick(View v)
	{
		switch (v.getId())
		{
		case R.id.act_takephotos_ll_take_photo:
			toggleFrameContent(mRlTakePhoto);
			break;

		case R.id.act_takephotos_ll_share:

			String content = mEtContent.getText().toString();
			if (TextUtils.isEmpty(content))
			{
				SDToast.showToast("请输入内容后分享");
				return;
			}

			UMImage umImage = null;
			String clickUrl = ApkConstant.SERVER_API_URL_PRE + ApkConstant.SERVER_API_URL_MID;

			if (mFileImageCompress != null)
			{
				umImage = new UMImage(TakephotosActivity.this, mFileImageCompress);
			}

			UmengSocialManager.openShare("分享", content, umImage, clickUrl, this, new SnsPostListener()
			{

				@Override
				public void onStart()
				{

				}

				@Override
				public void onComplete(SHARE_MEDIA arg0, int arg1, SocializeEntity arg2)
				{

				}
			});

			break;

		case R.id.act_takephotos_ll_jing:
			insertText("#");
			break;

		case R.id.act_takephotos_ll_at:
			insertText("@");
			break;

		case R.id.act_takephotos_ll_text_number:

			break;

		case R.id.act_takephotos_ib_take_photo:
			clickTakePhoto();
			break;

		case R.id.act_takephotos_ib_album:
			clickAlbum();
			break;

		case R.id.act_takephotos_ib_result_image_close:
			toggleFrameContent(mRlTakePhoto);
			break;

		default:
			break;
		}
	}

	private void insertText(String text)
	{
		Editable eb = mEtContent.getEditableText();
		int startPosition = mEtContent.getSelectionStart();
		eb.insert(startPosition, text);
	}

	/**
	 * 点击拍照
	 */
	private void clickTakePhoto()
	{
		File saveFileDir = App.getApplication().getExternalCacheDir();
		if (saveFileDir == null)
		{
			SDToast.showToast("得到图片缓存目录失败!");
		} else
		{
			mFileImage = new File(saveFileDir, IMAGE_NAME_TEMP);
			Intent intent = SDIntentUtil.getTakePhotoIntent(mFileImage);
			startActivityForResult(intent, REQUEST_CODE_TAKE_PHOTO);
		}
	}

	/**
	 * 点击从照片选择
	 */
	private void clickAlbum()
	{
		Intent intent = SDIntentUtil.getSelectLocalImageIntent();
		startActivityForResult(intent, REQUEST_CODE_SELECT_PHOTO);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data)
	{
		switch (requestCode)
		{

		case REQUEST_CODE_TAKE_PHOTO:
			if (resultCode == RESULT_OK)
			{
				dealImageResult(mFileImage);
			}
			break;
		case REQUEST_CODE_SELECT_PHOTO:
			if (resultCode == RESULT_OK)
			{
				mFileImage = new File(SDImageUtil.getImageFilePathFromIntent(data, this));
				dealImageResult(mFileImage);
			}
			break;

		default:
			break;
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	private void dealImageResult(File imageFile)
	{
		if (imageFile != null && imageFile.exists())
		{
			toggleFrameContent(mRlTakeResult);
			compressImageSizeToUploadSize(imageFile);
		}
	}

	private void compressImageSizeToUploadSize(final File originalFile)
	{
		AppHelper.showLoadingDialog("正在处理图片...");
		new Thread(new Runnable()
		{
			@Override
			public void run()
			{
				mFileImageCompress = new File(App.getApplication().getExternalCacheDir(), IMAGE_NAME_UPLOAD);
				if (originalFile.length() > MAX_UPLOAD_IMAGE_SIZE)
				{
					SDImageUtil.compressImageFileToNewFileSize(originalFile, mFileImageCompress, MAX_UPLOAD_IMAGE_SIZE);
				} else
				{
					SDFileUtil.copy(originalFile.getAbsolutePath(), mFileImageCompress.getAbsolutePath());
				}
				// 处理完成，在主线程显示
				SDHandlerUtil.runOnUiThread(new Runnable()
				{
					@Override
					public void run()
					{
						AppHelper.hideLoadingDialog();
						if (mFileImageCompress != null)
						{
							SDViewBinder.setImageViewByImagesScale(mIvResultImage,
									"file://" + originalFile.getAbsolutePath(), ImageLoaderManager.getOptionsNoCache());
						}
					}
				});
			}
		}).start();
	}

	private void toggleFrameContent(View content)
	{
		if (content != null)
		{
			for (int i = 0; i < mListContent.size(); i++)
			{
				View itemView = mListContent.get(i);
				if (itemView == content)
				{
					itemView.setVisibility(View.VISIBLE);
				} else
				{
					itemView.setVisibility(View.GONE);
				}
			}
		}
	}

}